//
//  GraphVC.m
//  eyr
//
//  Created by Tor Gjøsæter on 5/1/12.
//  Copyright (c) 2012 University of Bergen. All rights reserved.
//

#import "GraphVC.h"
#import "PGMidi.h"
#import "MiniGraphVC.h"
#import "Graph+Create.h"
#import "DataPointInTime.h"

@interface GraphVC () <PGMidiDelegate, PGMidiSourceDelegate>

@end

@implementation GraphVC

@synthesize myTimer;

@synthesize graphScroller;
@synthesize plotterV;
@synthesize steinVC;
@synthesize user;
@synthesize miniGraphVCs;

@synthesize popoverController;


int graphHeight = 0;
bool rising = true;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    static dispatch_once_t pred;
    
    //Set up of midi
    dispatch_once(&pred, ^{
        PGMidi *myMidi = [[PGMidi alloc] init];
        [myMidi enableNetwork:YES];
        
        [self setMidi:myMidi];
    });
    
    //Start timer
    myTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(graphTick) userInfo:nil repeats:YES];
    
}

- (void)graphTick{
 //   [self fadeInAndOut];
    [self.plotterV plot:graphHeight];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    
   // [plotterV plot:50];
    NSLog(@"Test");
   
//    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
//    [self setupScrollView:storyboard];
 
    [self setTitle:user.name];
    
}

- (void) fadeInAndOut{
    
    if(rising){
        graphHeight++;
    }else{
        graphHeight--;
    }
    if(graphHeight >= 255){
        rising = false;
    }
    if(graphHeight == 0){
        rising = true;
    }
 
    
}


- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
      
    if([segue.identifier isEqualToString:@"segueToGraphHelp"]){   
        NSLog(@"Segue to segueToGraphHelp");
        
        //  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
        //  UIViewController *helpGeneralVC = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"HelpGeneral"];
        
        if ([segue.destinationViewController respondsToSelector:@selector(setIdentifier:)]) {
            [segue.destinationViewController performSelector:@selector(setIdentifier:) 
                                                  withObject:@"HelpForGraph"];
        } 
        
        
        if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]]) //For å få vekk muchos poppus
        {
            UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue *)segue;
            [self.popoverController dismissPopoverAnimated:YES];
            self.popoverController = popoverSegue.popoverController; // might want to be popover's delegate and self.popoverController = nil on dismiss?
        }
        
    }   
    
}


- (void)viewDidUnload {
    [self setGraphScroller:nil];
    [self setPlotterV:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(void) plotImportedGraph:(Graph *) graph{
    NSArray *datapoints = [graph.dataPoints allObjects];
    
    for(int i = 0; i <datapoints.count; i++){
        if([[datapoints objectAtIndex:i] isKindOfClass:[DataPointInTime class]]){
            DataPointInTime *myDataPoint = [datapoints objectAtIndex:i]; 
            [self plot:myDataPoint.pressure];
        }
    }    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void) midiSource:(PGMidiSource*)midi midiReceived:(const MIDIPacketList *)packetList {
    [self.plotterV setBackgroundColor:[UIColor yellowColor]];
    const MIDIPacket *packet = &packetList->packet[0];
    for (int i = 0; i < packetList->numPackets; ++i)
    {
        int value = packet->data[1];
        NSNumber *v = [[NSNumber alloc] initWithUnsignedInt:value];
        
        graphHeight = [v intValue];
        /*
        [self performSelectorOnMainThread:@selector(plot:)
                               withObject:v
                            waitUntilDone:NO];
        
        */
        packet = MIDIPacketNext(packet);
    }
}

- (void) attachToAllExistingSources {
    for (PGMidiSource *source in midi.sources) { source.delegate = self; }
}

- (void) plot:(NSNumber *) value{
    int val = [value intValue];
    
    [self.plotterV plot:val];
}

- (void) setMidi:(PGMidi*)m {
    midi.delegate = nil;
    midi = m;
    midi.delegate = self;
    
    [self attachToAllExistingSources];
}

- (void) midi:(PGMidi*)midi sourceAdded:(PGMidiSource *)source {
    source.delegate = self;
    [self.view setBackgroundColor:[UIColor greenColor]];
}

- (void) midi:(PGMidi*)midi sourceRemoved:(PGMidiSource *)source {
    [self.view setBackgroundColor:[UIColor redColor]];
}
- (void) midi:(PGMidi*)midi destinationAdded:(PGMidiDestination *)destination {}
- (void) midi:(PGMidi*)midi destinationRemoved:(PGMidiDestination *)destination {}
/*
- (void) setupScrollView:(UIStoryboard*) storyboard{
    
    
    //Viewet for steinen
    self.steinVC = [storyboard instantiateViewControllerWithIdentifier:@"SteinVC"];
    
    float posx = 0;
    float steinVCWidth = 200;
    self.steinVC.view.frame = CGRectMake(posx, 0, steinVCWidth, 175); 
    [self.steinVC.view setBackgroundColor:[UIColor redColor]];
    
    posx = steinVCWidth;
    
    [[self graphScroller] addSubview:self.steinVC.view];
    
    //Denne bør kanskje lages i setteren til graphscroller?
    NSArray *graphs = [user.graphs allObjects];
    
    miniGraphVCs = [[NSMutableArray alloc] initWithCapacity:graphs.count];
    
    for(int i =0; i< graphs.count; i++){
        MiniGraphVC *myMiniGraphVC = [storyboard instantiateViewControllerWithIdentifier:@"MiniGraphVC"];
        myMiniGraphVC.delegate = self;
        UIView *myMiniGraphView = [myMiniGraphVC view];
        [miniGraphVCs addObject:myMiniGraphVC];
        
        
        if([[graphs objectAtIndex:i] isKindOfClass:[Graph class]]){
            Graph *myGraph = [graphs objectAtIndex:i]; 
            myMiniGraphVC.graph = myGraph;
            myMiniGraphVC.importDate.text = [Graph entireGraphDate:myGraph];
        }
        
        myMiniGraphView.frame =CGRectMake(posx, 0, 150, 150);
        //myMiniGraphVC.importDate = 
        
        [[self graphScroller] addSubview:myMiniGraphView];
        posx += 150.0;
    }
    [[self graphScroller] setContentSize:CGSizeMake(posx, 150.0)];
    
    
}*/


@end
